<template>
  <div class="login-page">
    <header>
      <h1>保养数据检查</h1>
      <p>选择账号登录</p>
    </header>
    
    <main>
      <div class="account-list-container">
        <table class="account-table">
          <thead>
            <tr>
              <th>编号</th>
              <th>名称</th>
              <th>手机号</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr 
              v-for="(account, index) in accounts" 
              :key="index"
              @click="handleAccountClick(account)"
              :class="{ 'row-loading': loadingAccountIndex === index }"
              class="clickable-row"
            >
              <td>{{ index + 1 }}</td>
              <td>{{ account.name }}</td>
              <td>{{ account.phone }}</td>
              <td>
                <span v-if="loadingAccountIndex === index" class="status-loading">登录中...</span>
                <span v-else class="status-ready">点击登录</span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { loginWithPassword, getStoreList, getTaskList } from '../api/index.js'
import { removeToken } from '../http/request.js'
import accountsData from '../accounts.js'

const accounts = ref(accountsData)
const loadingAccountIndex = ref(null)

// 触发登录并跳转事件
const emit = defineEmits(['login-success'])

async function handleAccountClick(account) {
  loadingAccountIndex.value = accounts.value.indexOf(account)
  
  try {
    // 0. Clear old token first to ensure fresh login
    console.log('Clearing old token...')
    removeToken()
    
    // 1. Login with username and password
    console.log('Logging in with:', account.phone, account.password)
    await loginWithPassword(account.phone, account.password)
    console.log('Login successful')
    
    // 2. Get store list
    console.log('Getting store list...')
    const stores = await getStoreList()
    console.log('Store list:', stores)
    
    // 3. Auto-select store with selected: true, fallback to first store
    let selectedStore = stores.find(store => store.selected)
    if (!selectedStore && stores.length > 0) {
      selectedStore = stores[0]
    }

    if (!selectedStore) {
      alert('未找到可用门店，请检查门店配置')
      loadingAccountIndex.value = null
      return
    }
    
    const storeId = selectedStore.code
    console.log('Selected store:', storeId)
    
    // 4. Get task list with storeId
    console.log('Getting task list with storeId:', storeId)
    
    const taskListParams = {
      current: 1,
      size: 10,
      dataScope: 'GARAGE',
      dataModel: 'CLIENT',
      code: 'MAINT',
      clientType: ['2', '5'],
      storeId: storeId,
      orders: {
        column: 'serviceDateTimestamp',
        asc: false
      }
    }
    
    const vehicleList = await getTaskList(taskListParams)
    console.log('Vehicle list:', vehicleList)
    
    // 发送成功事件，传递车辆数据
    emit('login-success', vehicleList)
    loadingAccountIndex.value = null
    
  } catch (error) {
    console.error('Login or data fetch failed:', error)
    alert('登录失败或获取数据失败: ' + (error.message || '未知错误'))
    loadingAccountIndex.value = null
  }
}
</script>

<style scoped>
.login-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

header {
  text-align: center;
  margin-bottom: 2rem;
}

header h1 {
  font-size: 2rem;
  margin-bottom: 0.5rem;
  color: #42b983;
}

header p {
  color: #64748b;
  font-size: 1rem;
}

/* Account Table Styles */
.account-list-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.account-table {
  width: 100%;
  border-collapse: collapse;
}

.account-table thead {
  background-color: #42b983;
  color: white;
}

.account-table th,
.account-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.account-table tbody tr {
  transition: background-color 0.2s;
}

.account-table tbody tr:hover {
  background-color: #f8fafc;
}

.clickable-row {
  cursor: pointer;
}

.row-loading {
  background-color: #fff3cd;
  opacity: 0.8;
}

.status-loading {
  color: #ff9800;
  font-weight: bold;
}

.status-ready {
  color: #42b983;
}
</style>
